package ecommerce.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.sql.Statement;

import java.util.Properties;

import ecommerce.exception.EcommerceException;

public class ConexionBD {
    private static ConexionBD instance = null;
    
    private ConexionBD() {
    }
 
    public static ConexionBD getInstance() {
        if(instance == null)
            instance = new ConexionBD();
        
        return instance;
    }
 
    public Connection getConexionBD() throws EcommerceException {
        //Obtener la conexion a la BD
        Connection cn = null;
        String driver = null;
        String url = null;
        String user = null;
        String pass = null;
        try{
            
            Properties prop = new Properties();
            prop.load(getClass().getResourceAsStream("config.properties"));
            
            driver = prop.getProperty("driver");
            url = prop.getProperty("url");
            user = prop.getProperty("user");
            pass = prop.getProperty("pass");
            
            Class.forName(driver);
            cn = DriverManager.getConnection(url,user,pass);
            
        }catch(SQLException e){
            //Registrar el error en el LOG y retorna un Exception personalizado
            EcommerceLog.error(e);
            throw new EcommerceException("Error al conectarse con la BD");            
        }catch(Exception e){
            //Registrar el error en el LOG y retorna un Exception personalizado
             EcommerceLog.error(e);
            throw new EcommerceException("Error al cargar el Driver de la BD");
        }
        
        return cn;
    }
    
    public void close(Statement stm){
        if(stm != null) {
            try{
                stm.close();
            }catch(Exception e){
                EcommerceLog.error(e);
            }
        }
    }
    
    public void close(Connection cn){
        if(cn != null) {
            try{
                cn.close();
            }catch(Exception e){
                EcommerceLog.error(e);
            }
        }
    }
    
    public void close(ResultSet rs){
        if(rs != null) {
            try{
                rs.close();
            }catch(Exception e){
                EcommerceLog.error(e);
            }
        }
    }
    
}
